<template>
  <div class="wrap">
    <div class="title font14">{{ $t('configLazyLoad.businessConfig.satisfactionDetail') }}</div>
    <el-form
      class="main"
      ref="form"
      :model="form"
      size="small"
      :rules="rules"
      label-position="right"
      label-width="120px"
    >
      <el-form-item :label="$t('configLazyLoad.businessConfig.title')" prop="title">
        <el-input v-model.trim="form.title" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.businessConfig.textTemplate')" prop="smsTemplate.templateId">
        <el-select v-model="form.smsTemplate.templateId" style="width: 320px">
          <el-option v-for="(one, index) in templateArr" :key="index" :label="one.name" :value="one._id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.businessConfig.questionnaireShow')" prop="content">
        <el-input type="textarea" :rows="3" v-model.trim="form.content" maxlength="500"></el-input>
      </el-form-item>
      <el-form-item label="整体满意度" prop="global">
        <div>
          <el-switch v-model="form.overallSatisfaction" active-color="#409EFF" inactive-color="#DCDFE6"></el-switch>
          <span class="tip"
            >注意：如果想使用工单满意度报表，则需要开启整体满意度，工单满意度报表只会统计整体满意度的评价数据</span
          >
        </div>
        <globalStarsItem
          v-if="form.overallSatisfaction"
          ref="globalStarsItem"
          :item="form.satisfaction"
        ></globalStarsItem>
      </el-form-item>
      <el-form-item label="子项满意度设置">
        <el-switch v-model="form.subSatisfaction" active-color="#409EFF" inactive-color="#DCDFE6"></el-switch>
        <div class="border" v-if="form.subSatisfaction">
          <el-form-item :label="$t('configLazyLoad.businessConfig.topic')" prop="chooseTitle" label-width="50px">
            <el-input v-model.trim="form.chooseTitle" maxlength="50"></el-input>
          </el-form-item>
          <el-form-item :label="$t('configLazyLoad.businessConfig.option')" prop="choose" label-width="50px">
            <rate
              ref="rate"
              v-for="(item, index) in form.choose"
              :item="item"
              :index="index"
              :key="index"
              @remove="deleteItem"
            ></rate>
            <el-button class="primary_btn" @click.stop="addItem" size="mini">
              <i class="el-icon-plus"></i>{{ $t('configLazyLoad.businessConfig.addingItems') }}
            </el-button>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.businessConfig.otherProblems')" prop="otherQuestionTitle">
        <el-input v-model.trim="form.otherQuestionTitle" maxlength="50"></el-input>
        <el-checkbox v-model="form.otherQuestionFlag">{{ $t('configLazyLoad.businessConfig.descTip') }}</el-checkbox>
      </el-form-item>
      <el-form-item style="text-align: right">
        <el-button size="mini" class="primary_btn" type="primary" @click.stop="save">{{ $t('public.save') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import rate from './base/starsItem'
import globalStarsItem from './base/globalStarsItem'
import { cloneDeep } from 'lodash'
export default {
  name: 'satisfaction',
  data() {
    let self = this
    let validate2 = (rule, value, callback) => {
      if (self.form.otherQuestionFlag && !value) {
        callback(new Error(this.$t('validate.required')))
      } else {
        callback()
      }
    }

    return {
      templateArr: [],
      smsSign: [],
      baseForm: {
        subSatisfaction: false, // 其他问题开关状态
        _id: '',
        overallSatisfaction: true,
        satisfaction: {
          subTitle: '整体满意度',
          subs: [
            {
              name: this.$t('configLazyLoad.businessConfig.verySatisfied'), // 一级标签
              tags: [] // 二级标签
            },
            {
              name: this.$t('configLazyLoad.businessConfig.satisfied'), // 一级标签
              tags: [] // 二级标签
            },
            {
              name: this.$t('configLazyLoad.businessConfig.general'), // 一级标签
              tags: [] // 二级标签
            },
            {
              name: this.$t('configLazyLoad.businessConfig.dissatisfied'), // 一级标签
              tags: [] // 二级标签
            },
            {
              name: this.$t('configLazyLoad.businessConfig.veryDissatisfied'), // 一级标签
              tags: [] // 二级标签
            }
          ]
        },
        title: '', // 工单满意度标题
        smsTemplate: { templateId: '' }, // 短信模板信息
        chooseTitle: '', // 单选标题
        content: this.$t('configLazyLoad.businessConfig.questionnaireTip'), //问卷说明
        choose: [
          {
            subTitle: '', // 子标题
            subs: [
              {
                name: this.$t('configLazyLoad.businessConfig.verySatisfied'), // 一级标签
                tags: [] // 二级标签
              },
              {
                name: this.$t('configLazyLoad.businessConfig.satisfied'), // 一级标签
                tags: [] // 二级标签
              },
              {
                name: this.$t('configLazyLoad.businessConfig.general'), // 一级标签
                tags: [] // 二级标签
              },
              {
                name: this.$t('configLazyLoad.businessConfig.dissatisfied'), // 一级标签
                tags: [] // 二级标签
              },
              {
                name: this.$t('configLazyLoad.businessConfig.veryDissatisfied'), // 一级标签
                tags: [] // 二级标签
              }
            ]
          }
        ],
        otherQuestionFlag: false, // 是否启用其他问题
        otherQuestionTitle: '' // 其他问题
      },
      form: cloneDeep(this.baseForm),
      rules: {
        title: [{ required: true, message: this.$t('validate.required'), trigger: 'blur' }],
        chooseTitle: [{ required: true, message: this.$t('validate.required'), trigger: 'blur' }],
        'smsTemplate.templateId': [{ required: true, message: this.$t('validate.required'), trigger: 'change' }],
        otherQuestionTitle: [{ validator: validate2, trigger: 'blur' }],
        content: [{ required: true, message: this.$t('validate.required'), trigger: 'blur' }]
      }
    }
  },
  components: {
    rate,
    globalStarsItem
  },
  computed: {},
  methods: {
    // 添加子项
    addItem() {
      this.form.choose.push(cloneDeep(this.baseForm.choose[0]))
    },
    deleteItem(index) {
      this.$confirm(this.$t('configLazyLoad.businessConfig.deleteTip'), this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      })
        .then(() => {
          this.form.choose.splice(index, 1)
        })
        .catch(() => {})
    },
    save() {
      let isValid = false
      this.$refs.form.validate((valid) => {
        isValid = valid
      })
      if (!this.form.subSatisfaction && !this.form.overallSatisfaction) {
        this.$message.error('整体满意度与子项满意度设置至少要开启一个！')
        return false
      }
      if (this.form.subSatisfaction && isValid) {
        isValid = this.$refs.rate.every((item) => {
          return item.submit()
        })
      }
      if (!isValid) {
        return
      }
      if (this.form.overallSatisfaction && isValid) {
        isValid = this.$refs.globalStarsItem.submit()
      }
      if (!isValid) {
        return
      }
      if (this.form.subSatisfaction && this.form.choose.length < 1) {
        this.$message.error(this.$t('configLazyLoad.businessConfig.leastTip'))
        return
      }
      this.$confirm(this.$t('configLazyLoad.businessConfig.saveTip'), this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      })
        .then(() => {
          let form = this.form
          // _id为空是添加 否则是编辑
          if (!form._id) {
            delete form._id
          }
          let smsTemp =
            this.templateArr.filter((item) => {
              if (item._id === this.form.smsTemplate.templateId) {
                return true
              }
            })[0] || {}
          let sms = { template: smsTemp.content, smsChannel: smsTemp.smsChannel[0] }
          for (let j = 0; j < this.smsSign.length; j++) {
            if (smsTemp.sign === this.smsSign[j]._id) {
              sms.templateSign = this.smsSign[j].subcode + '_' + this.smsSign[j].name
            }
          }
          Object.assign(this.form.smsTemplate, sms)
          console.log(form)
          this.$store.dispatch('saveAppraiseTemplate', form).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('configLazyLoad.businessConfig.saveSuccess'))
            }
          })
        })
        .catch(() => {})
    },
    fetchData() {
      this.form = cloneDeep(this.baseForm)
      this.$store.dispatch('getAppraiseTemplates', {}).then((res) => {
        if (res.success) {
          let data = res.data[0] || {}
          for (let i in this.form) {
            if (data[i] || data[i] === false) {
              this.form[i] = data[i]
            }
          }
          this.templateChange()
        }
      })
    },
    templateChange() {
      let isHas = this.templateArr.some((item) => {
        if (item._id === this.form.smsTemplate.templateId) {
          return true
        }
      })
      if (this.form.smsTemplate.templateId && !isHas) {
        this.$message.error(this.$t('configLazyLoad.businessConfig.selectTip'))
        this.form.smsTemplate.templateId = ''
      }
    }
  },
  beforeMount() {
    let p1 = this.$store.dispatch('getCache', { type: 'smsTemplate' }).then((res) => {
      this.templateArr = (res || []).filter((item) => item.type === 'flow')
    })
    let p2 = this.$store.dispatch('getCache', { type: 'smsSign' }).then((res) => {
      this.smsSign = res
    })
    Promise.all([p1, p2]).then(() => {
      this.fetchData()
    })
  }
}
</script>

<style scoped lang="stylus">
@import '../../../../assets/common.styl'
.title
  line-height 42px
  padding-left 20px
  border-bottom 1px solid $c-border2
.main {
  padding 18px 20px
  height calc(100vh - 130px)
  overflow-y auto
}
.border
   border 1px solid $c-border2
   padding 20px
   margin-top: 12px
.tip {
  color: #409EFF;
  margin-left: 12px;
  font-size: 12px;
}
</style>
